local Archy = LibStub("AceAddon-3.0"):GetAddon("Archy")
local LDB = Archy:NewModule("LDB", "AceEvent-3.0", "AceTimer-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("Archy")
local ldb = LibStub("LibDataBroker-1.1")
local QT = LibStub("LibQTip-1.0");
local continentNames = {
	[WORLDMAP_COSMIC_ID] = L["Cosmic"], -- That constant is -1
	[0] = L["World"],
	[1] = L["Kalimdor"],
	[2] = L["Eastern Kingdoms"],		
	[3] = L["Outland"],
	[4] = L["Northrend"],
	[5] = L["Deepholm"],
}
local db

function LDB:OnInitialize()
end
function LDB:SetupAdditionalFeeds()
	local feed_digsites = ldb:NewDataObject("Archy_Digsites", {
		type = "data source",
		icon = "Interface\Archeology\Arch-Icon-Marker.blp",
		text = L["Dig Sites"],
		OnEnter = function(self)
			local tooltip, numCols, lineNum = LDB:SetupTooltip(self)
			if not tooltip then return end
			self.tooltip = tooltip
			if Archy.archData:PlayerHasArchaeology() then
				LDB:DrawDigsiteTooltip(numCols, lineNum)
			end
			LDB:TooltipFooter(numCols, lineNum)
			self.tooltip:Show()
		end,
		OnLeave = function(self)
			QT:Release(self.tooltip)
			tooltip = nil
		end,
	})

	local feed_artifacts = ldb:NewDataObject("Archy_Artifacts", {
		type = "data source",
		icon = "Interface\Icons\TRADE_ARCHAEOLOGY_TITAN_FRAGMENT.BLP",
		text = L["Artifacts"],
		OnEnter = function(self)
			local tooltip, numCols, lineNum = LDB:SetupTooltip(self)
			if not tooltip then return end
			self.tooltip = tooltip
			if Archy.archData:PlayerHasArchaeology() then
				LDB:DrawArtifactTooltip(numCols, lineNum)
			end
			LDB:TooltipFooter(numCols, lineNum)
			self.tooltip:Show()
		end,
		OnLeave = function(self)
			QT:Release(self.tooltip)
			tooltip = nil
		end,
	})
end

function LDB:OnEnable()
	db = Archy.db.profile
	self:RegisterMessage("ArchyLDBTooltip", "OnLDBTooltip")
	self:RegisterMessage("ArchyConfigChanged", "OnConfigChanged")
end
function LDB:OnDisable()
	self:UnregisterMessage("ArchyLDBTooltip")
	self:UnregisterMessage("ArchyConfigChanged")
end

function LDB:OnConfigChanged()
	db = Archy.db.profile
end

function LDB:OnLDBTooltip(event, self)
	local tooltip, numCols, lineNum = LDB:SetupTooltip(self)
	if not tooltip then return end
	self.tooltip = tooltip
	if Archy.archData:PlayerHasArchaeology() then
		if db.ldb.artifacts then
			numCols, lineNum = LDB:DrawArtifactTooltip(numCols, lineNum)
		end
		if db.ldb.digsites then
			lineNum = tooltip:AddLine("");
			numCols, lineNum = LDB:DrawDigsiteTooltip(numCols, lineNum, db.ldb.filterDigsites)
		end
	end
	LDB:TooltipFooter(numCols, lineNum)
	self.tooltip:Show()
end

local function NormalFontString(msg)
	return NORMAL_FONT_COLOR_CODE .. msg .. "|r"
end

local function SetupTexture(texture)
	return format("|T%s:18:18:0:1:128:128:4:60:4:60|t", texture)
end

function LDB:DrawArtifactTooltip(numCols, lineNum)
	local tooltip = QT:Acquire("ArchyTooltip")

	lineNum = tooltip:AddLine(" ", NormalFontString(L["Race"]), NormalFontString(L["Artifact"]), NormalFontString(L["Progress"]), NormalFontString(L["Key Stones"]))
	local artifacts = Archy.archData:GetActiveArtifacts()
	if artifacts then
		for race, artifact in pairs(artifacts) do
			local artifactName;
			if artifact.rarity == 0 then
				artifactName = GRAY_FONT_COLOR_CODE .. artifact.name .. "|r";
			else
				artifactName = Archy.rareItemColorCode .. artifact.name .. "|r";
			end
			local progress;
			if artifact.fragments >= artifact.totalFragments then
				progress = "|cFF00FF00" .. artifact.fragments .. "|r";
			else
				progress = "|cFFFFFFFF" .. artifact.fragments .. "|r";
			end
			progress = progress .. "/|cFFFFFFFF" .. artifact.totalFragments .. "|r";

			local keystones = format("|cFFFFFF00%s/%s|r", artifact.keystonesAvailable, artifact.sockets);
			if artifact.sockets == 0 and artifact.keystonesAvailable == 0 then
				keystones = "";
			end
			
			lineNum = tooltip:AddLine(SetupTexture(artifact.race.texture), artifact.race.name, artifactName)
			tooltip:SetCell(lineNum, 4, progress, "CENTER");
			tooltip:SetCell(lineNum, 5, keystones, "CENTER");
		end
		lineNum = tooltip:AddLine(" ", " ", " ", " ", " ");
	end
	return numCols, lineNum
end

function LDB:DrawDigsiteTooltip(numCols, lineNum, filter)
	local tooltip = QT:Acquire("ArchyTooltip")
	
	local currSites = {}
	for cid, zlist in ipairs{GetMapContinents()} do
		if filter == nil or filter == false or cid == GetCurrentMapContinent() then
			currSites[cid] = Archy.archData:GetContinentSites(cid, false)
		end
	end

	if currSites then
		for continent, conSites in pairs(currSites) do
			if conSites and #conSites > 0 then
				lineNum = tooltip:AddLine(" ");
				tooltip:SetCell(lineNum, 1,"  " .. ORANGE_FONT_COLOR_CODE .. continentNames[continent] .. "|r", "LEFT", numCols)
				lineNum = tooltip:AddLine(" ")
				tooltip:SetCell(lineNum, 1, " ", "LEFT", 1)
				tooltip:SetCell(lineNum, 2, NormalFontString(L["Fragment"]), "LEFT", 1)
				tooltip:SetCell(lineNum, 3, NormalFontString(L["Dig Site"]), "LEFT", 1)
				tooltip:SetCell(lineNum, 4, NormalFontString(L["Zone"]), "LEFT", 1)
				tooltip:SetCell(lineNum, 5, "", "LEFT", 1)
				for _,site in pairs(conSites) do
					if site.race then
						lineNum = tooltip:AddLine(SetupTexture(site.race.texture), site.race.name, site.name, site.zone.name, "")
					else
						lineNum = tooltip:AddLine("", "", site.name, site.zone.name, "")
					end
				end
				lineNum = tooltip:AddLine(" ", " ", " ", " ", " ");
			end
		end
	end
	return numCols, lineNum
end


function LDB:SetupTooltip(self)
	if not QT then return end
	local tooltip = QT:Acquire("ArchyTooltip", 5, "LEFT", "LEFT", "LEFT", "CENTER", "CENTER")
--	tooltip:SetScale(1)
	tooltip:SetAutoHideDelay(0.1, self)
	tooltip:EnableMouse()
	tooltip:SmartAnchorTo(self)
	tooltip:Hide()
	tooltip:Clear()
	tooltip:UpdateScrolling()
	local t = {}
	local numCols = 5
	for i=1,5 do t[i] = "LEFT" end
	tooltip:SetColumnLayout(numCols, unpack(t))
	
	local lineNum = tooltip:AddHeader(" ");
	tooltip:SetCell(lineNum, 1, ORANGE_FONT_COLOR_CODE .. L["Archy"] .. "|r", "CENTER", numCols)
	local colIndex = 0
	local t = {}
	
	if Archy.archData:PlayerHasArchaeology() then
		lineNum = tooltip:AddLine(" ", " ", " ", " ", " ");
		
		local skill = Archy:RankDisplay()
		tooltip:SetCell(lineNum, 1, string.format("%s%s|r%s", NORMAL_FONT_COLOR_CODE, L["Skill: "], skill), "CENTER", numCols)
	else
		lineNum = tooltip:AddLine(" ", " ", " ", " ", " ");
		tooltip:SetCell( lineNum, 1, L["Learn Archaeology in your nearest major city!"], "CENTER", numCols);
	end
	return tooltip, numCols, lineNum
end

function LDB:TooltipFooter(numCols, lineNum)
	local tooltip = QT:Acquire("ArchyTooltip")
	lineNum = tooltip:AddLine(" ");
	tooltip:SetCell(lineNum, 1, "|cFF00FF00" .. L["Left-Click to toggle Archy"] .. "|r", "LEFT", numCols);
	lineNum = tooltip:AddLine(" ");
	tooltip:SetCell(lineNum, 1, "|cFF00FF00" .. L["Shift Left-Click to toggle Artifact and Dig Site lists"] .. "|r", "LEFT", numCols);
	lineNum = tooltip:AddLine(" ");
	tooltip:SetCell(lineNum, 1, "|cFF00FF00" .. L["Ctrl Left-Click to open Archy's options"] .. "|r", "LEFT", numCols);
	lineNum = tooltip:AddLine(" ");
	tooltip:SetCell(lineNum, 1, "|cFF00FF00" .. L["Right-Click to lock/unlock Archy"] .. "|r", "LEFT", numCols);
	lineNum = tooltip:AddLine(" ");
	tooltip:SetCell(lineNum, 1, "|cFF00FF00" .. L["Middle-Click to display the Archaeology window"] .. "|r", "LEFT", numCols);
end